package com.moli.iov.open.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.moli.iov.open.authentication.TokenServices;
import com.moli.iov.open.constants.Constant;
import com.moli.iov.rest.GenericCode;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.model.dto.res.ClientDetailsResDto;
import com.moli.iov.util.ResponseUtils;
import com.moli.iov.util.StringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * <p>
 * token拦截器
 * 校验是否有token
 * </p>
 *
 * @author zql
 * @since 2019/8/30 11:54
 */
@Slf4j
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private TokenServices tokenServices;

  @Value("${token.tokenHeader}")
  private String tokenHeader;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    try{
      log.info("tokenHeader头：{}", tokenHeader);
      String access_token = request.getHeader("access_token");
      if(StringUtil.isBlank(access_token)){
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.TOKEN_PARAM_ERROR)),
            HttpStatus.SC_OK);
        log.info("token拦截器 获取不到 access_token");
        return false;
      }

      ClientDetailsResDto clientDetailsResDto = tokenServices.validAccessToken(access_token);
      log.info("根据access_token 获取 客户端信息：{}", clientDetailsResDto);
      if(clientDetailsResDto == null){
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.TOKEN_NON)),
            HttpStatus.SC_OK);
        return false;
      }

      request.setAttribute(Constant.DEFAULT_REQUEST_CLIENT, clientDetailsResDto);

      return true;
    }catch(Exception e){
      ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.SYS_BIZ)),
          HttpStatus.SC_OK);
      log.error("token拦截器 异常", e);
      return false;
    }

  }
}
